package cn.sc.allinpay.allfavour.business.checkdetail;

import android.app.Activity;
import android.content.DialogInterface;
import android.os.Bundle;

import com.alibaba.fastjson.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.pai.common.listener.OnPromptListener;
import cn.pai.mvp.callback.MpCallBack;
import cn.pai.mvp.intervenor.Intervenor;
import cn.pai.mvp.presenter.PaiPresenter;
import cn.sc.allinpay.allfavour.app.Constant;
import cn.sc.allinpay.allfavour.base.db.DbDao;
import cn.sc.allinpay.allfavour.business.common.data.CashierData;
import cn.sc.allinpay.allfavour.business.common.data.CheckCouponData;
import cn.sc.allinpay.allfavour.business.common.data.CheckCouponsRecord;
import cn.sc.allinpay.allfavour.business.common.dialog.CheckResultDialog;
import cn.sc.allinpay.allfavour.module.device.DeviceLogin;
import cn.sc.allinpay.allfavour.module.printer.IPrinter;
import cn.sc.allinpay.allfavour.module.printer.PrintData;
import cn.sc.allinpay.allfavour.module.printer.PrintManager;

/**
 * 验券详情 presenter
 * author：pany
 * on 2017/12/1 11:27
 */
public class CheckDetailPresenter extends PaiPresenter<CheckDetailContract.View> implements CheckDetailContract.Presenter {

    private CheckDetailModel model = new CheckDetailModel();

    private ArrayList<CheckCouponData> checkDatas;
    private List<CheckCouponsRecord> checkRecords;
    private IPrinter printer;

    @Override
    protected Intervenor createIntervenor() {
        return new Intervenor() {
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                Bundle bundle = view.getBundle();
                checkDatas = bundle.getParcelableArrayList(Constant.BundleKey.CHECKCOUPON);
            }

            @Override
            public void onResume() {
                super.onResume();
                DeviceLogin.login(view.getContext());
            }

            @Override
            public void onPause() {
                super.onPause();
                DeviceLogin.logout();
            }
        };
    }

    @Override
    public void start() {
        if (initData()) {
            initView();
        } else {
            view.toast("初始化数据失败");
            view.finish();
        }
    }

    /**
     * 数据初始化
     *
     * @return
     */
    private boolean initData() {
        if (checkDatas == null || checkDatas.isEmpty()) {
            view.toast("验券数据为空");
            return false;
        }
        return true;
    }

    /**
     * 初始化视图
     */
    private void initView() {
        for (int i = 0; i < checkDatas.size(); i++) {
            CheckCouponData coupons = checkDatas.get(i);
            if (coupons.isUse()) {
                if (coupons.getType() == 0) {//金额
                    view.addCouponView(coupons.getCouponName(), "-" + coupons.getUseAmt() + coupons.getUnit(), coupons.getRemark());
                } else {
                    view.addCouponView(coupons.getCouponName(), "-" + coupons.getUseNumber() + coupons.getUnit(), coupons.getRemark());
                }
            }
        }
    }

    @Override
    public void reqCheckCoupon() {
        view.loading("验券中...");
        model.reqCheckCoupon(checkDatas, new MpCallBack<JSONObject, String>() {
            @Override
            public void onSuccess(JSONObject resp) {
                view.loaded();
                final String orderId = resp.getJSONObject("data").getString("orderId");
                CashierData operator = model.getGlobal().getCashierData();
                final String trsTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                saveRecord(orderId, trsTime, checkDatas, operator);
                CheckResultDialog resultDialog = new CheckResultDialog(view.getContext(), checkDatas, operator);
                resultDialog.setOnDialogListener(new CheckResultDialog.OnDialogListener() {
                    @Override
                    protected void onConfirm() {
                        print(orderId, trsTime);
                    }
                });
                resultDialog.show();
            }

            @Override
            public void onFailure(String response, String message) {
                view.loaded();
                view.prompt(message);
            }
        });
    }

    /**
     * 保存验券流水
     */
    private void saveRecord(String orderId, String transTime, List<CheckCouponData> couponsDatas, CashierData operator) {
        DbDao<CheckCouponsRecord> dbDao = model.getDao(CheckCouponsRecord.class);
        checkRecords = new ArrayList<>();
        for (int i = 0; i < couponsDatas.size(); i++) {
            CheckCouponData coupons = couponsDatas.get(i);
            CheckCouponsRecord record = new CheckCouponsRecord();
            record.setTransNo(orderId + coupons.getCouponNo());
            record.setOrderId(orderId);
            record.setCouponCode(coupons.getCouponNo());
            record.setCouponNo(coupons.getCouponNo());
            record.setCouponName(coupons.getCouponName());
            record.setBalance(coupons.getBalance());
            record.setUnit(coupons.getUnit());
            record.setType(coupons.getType());
            record.setOperator(operator.getCashierNo());
            record.setOperatorName(operator.getCashierName());
            record.setTransDate(transTime.substring(0, 8));
            record.setTransTime(transTime.substring(8));
            record.setUseAmt(coupons.getUseAmt());
            record.setUseNum(coupons.getUseNumber());
            record.setDesc(coupons.getRemark());
            checkRecords.add(record);
            dbDao.add(record);
        }
    }

    public void print(final String orderNo, final String trsTime) {
        view.loading("验券成功，正在打印...");
        PrintData data = new PrintData();
        data.setMerchantName(model.getGlobal().getConfigData().getMerName());
        data.setTerminalId(model.getGlobal().getConfigData().getTerId());
        data.setOperNo(model.getGlobal().getCashierData().getCashierNo());
        data.setOperName(model.getGlobal().getCashierData().getCashierName());
        data.setTime(trsTime);
        data.setTransName("验券");
        data.setOrderId(orderNo);//验券订单号
        data.setCheckRecords(checkRecords);
        printer = PrintManager.createPrinter(PrintManager.PRINT_CHECK, data);
        printer.print(new IPrinter.OnPrintListener() {
            @Override
            public void onStart(int step) {

            }

            @Override
            public void onSuccess(int step) {
                view.loaded();
                view.prompt(false, "打印成功", new OnPromptListener("确定") {
                    @Override
                    public void onPositive(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        view.setResult(Activity.RESULT_OK, null);
                        view.finish();
                    }
                });
            }

            @Override
            public void onFail(int code, String msg) {
                view.loaded();
                view.prompt(false, msg + ",是否继续打印", new OnPromptListener("确定", "取消") {
                    @Override
                    public void onPositive(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        print(orderNo, trsTime);
                    }

                    @Override
                    public void onNegative(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        view.setResult(Activity.RESULT_OK, null);
                        view.finish();
                    }
                });
            }
        });
    }
}
